package com.hyh.admin.tool;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hyh.ad.common.constants.Constants;
import com.hyh.ad.common.core.domain.model.SysUser;
import com.hyh.ad.common.core.redis.CacheClient;
import com.hyh.ad.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;

@Component
public class JwtUtil {

    @Autowired
    public  CacheClient cacheClient;

    /**
     * 生成token
     * Algorithm.HMAC256():使用HS256生成token,密钥则是用户的密码
     * withClaim():存入需要保存在token里的信息
     * withExpiresAt():设置过期时间
     * sign():生成token
     * @param user
     */

    private static final String SING = IdUtils.randomUUID();

    public  String getToken(SysUser user) {

        // 设置token过期时间
        Calendar instance= Calendar.getInstance();
        instance.add(Calendar.DATE,7);
        String token="";
        token= JWT.create()
                .withClaim("id",String.valueOf(user.getId())) //设置载荷
                .withClaim("username",user.getUsername())
                .withClaim("password",user.getPassword())
                //.withExpiresAt(instance.getTime()) //设置令牌过期的时间
                .sign(Algorithm.HMAC256(SING));
        //将token存入redis
        cacheClient.setObject(Constants.TOKEN+token,user,Constants.TOKEN_EXPIRATION, TimeUnit.MINUTES);
        return token;
    }
    /**，
     * 验证token  合法性
     * verify()：验证token是否正确
     * @param token
     */
    public  DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }
}
